<?php

namespace App\Http\Controllers;

use App\Http\Logic\Dev;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;

class DevController extends Controller
{
    // 执行SQL请求
    public function execute(Request $request): JsonResponse
    {
        // 校验数据
        try {
            $params = $request->validate([
                'sql' => ['required', 'string', 'max:2000'],
            ]);

            // 记录日志（执行前）
            $logId = Dev::getInstance()->insertLog(
                [
                    'uid' => $this->getUid($request),
                    'sql' => $params['sql'],
                ]
            );

            $sql = $this->sanitizeSql($params['sql']);

            $this->validateSqlType($sql);

            // 执行查询
            $results = DB::select($sql);

            // 处理导出数据
            if ($request->has('export')) {
                return $this->retSuccess($results);
            }

            // 分页数据
            $data = $this->paginateResults($results);
            return $this->retSuccess($data);
        } catch (Exception $e) {
            // 更新日志记录错误
            if (isset($logId)) {
                Dev::getInstance()->updateLog($logId, $e->getMessage());
            }
            return $this->retError(-1, $e->getMessage());
        }
    }

    // SQL净化处理
    private function sanitizeSql($sql): string|null
    {
        return preg_replace('/\s+/', ' ', trim($sql));
    }

    /**
     * SQL类型验证
     * @throws Exception
     */
    private function validateSqlType($sql): void
    {
        if (!preg_match('/^select\s+/i', $sql)) {
            throw new Exception('只允许执行SELECT查询语句');
        }
    }

    // 手动分页处理
    private function paginateResults($items): array
    {
        $perPage = request()->input('size', 10);
        $page = request()->input('page', 1);
        $offset = ($page * $perPage) - $perPage;
        return ['list' => array_slice($items, $offset, $perPage), 'total' => count($items)];
    }
}
